using System;
using System.Collections.Generic;
using System.Text;

using Multiplicity.Runtime.Serialization.Binary;

namespace Multiplicity.Reflection {

    class CustomModifierElement {

        public readonly bool Required;
        public readonly uint TypeDefOrRef;

        public CustomModifierElement(bool required, uint type) {
            this.Required = required;
            this.TypeDefOrRef = type;
        }

        public static CustomModifierElement[] Parse(MetadataParser parser) {

            List<CustomModifierElement> modifiers = new List<CustomModifierElement>();

            while (true) {
                SignatureElement element = (SignatureElement)parser.PeekByte();
                
                bool required;
                uint typeToken;

                if (element == SignatureElement.CModOptional) {
                    parser.ReadByte();

                    required = false;
                }
                else if (element == SignatureElement.CModRequired) {
                    parser.ReadByte();

                    required = true;
                }
                else {
                    break;
                }

                typeToken = parser.ReadCompressedToken(CodedTokenFamilyType.TypeDefOrRef);
                modifiers.Add(new CustomModifierElement(required, typeToken));
            }

            return modifiers.ToArray();
        }
    }
   
    
    class FieldSig : Signature {

        const byte FieldElement = 0x6;

        public readonly CustomModifierElement[] Modifiers;
        public readonly TypeElementBase Type;

        public FieldSig(Blob blob) {

            using (MetadataParser parser = blob.Parse()) {
                if (parser.ReadByte() != FieldElement) {
                    MetadataException.ThrowSignatureBlobException();
                }

                this.Modifiers = CustomModifierElement.Parse(parser);
                this.Type = TypeElementBase.Parse(parser);
            }
        }

    }
}
